<template>
  <Container class="policy-fund-edit">
    <div class="container-header title title-center" slot="header">
      {{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <div class="bgs">
      <Form :label-width="80" class="form" :model="form" ref="form" :rules="rules">
        <FormItem label="政策名称" prop="name">
          <Input
            :maxlength="20"
            class="common-width"
            v-model.trim="form.name"
            placeholder="请输入2-20位字符的政策名称"/>
        </FormItem>
        <FormItem label="生效时间" prop="date">
          <DatePicker
            v-model="form.date"
            type="daterange"
            placeholder="请选择生效时间"
            class="common-width"
          ></DatePicker>
        </FormItem>
        <FormItem label="添加品牌">
          <Select v-model="inputModel" @on-change="onChange" multiple class="common-width">
            <Option
              v-for="item in list.brandList"
              :value="item.brandId"
              :key="item.brandId"
            >{{item.brandName}}</Option>
          </Select>
        </FormItem>
      </Form>
      <div class="table-content">
        <p class="describle" v-if="list.data.length<=0">暂时没有添加品牌哦,可以在下面下拉框添中加品牌</p>
        <div v-else>
          <!-- <div v-for="(item, idx) in list.tableInfoList" :key="idx">
            <Table border :columns="item.columns" :data="item.data"></Table>
          </div> -->
          <Table border :columns="list.columns" :data="list.data"></Table>
        </div>
      </div>
    </div>

    <Loader :status="status" @refresh="getInfo"></Loader>
    <div class="container-footer bg-white" slot="footer">
      <div>
        <Button   :disabled='isDisabled' type="primary" class="mr" size="large" @click="onSave">保存</Button>
        <Button type="primary" class="mr" size="large" @click="jumpPrevPage">取消</Button>
      </div>
    </div>
  </Container>
</template>
<script>
import table from "@/table";
import data from "./edit/FundEditItemData";
import { formatDate, getOriginData } from "@/util";
import { Input } from "view-design";
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      id: this.$route.query.id || "",
      title: "",
      status: "pass",
      isDisabled: false,
      inputModel: [],
      form: {
        name: "",
        date: []
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: "blur" }],
        date: [
          {
            required: true,
            message: "请选择开始时间",
            trigger: "blur",
            type: "array",
            fields: {
              0: { type: "date", required: true, message: "请输入起止日期" },
              1: { type: "date", required: true, message: "请输入起止日期" }
            }
          }
        ]
      },
      options: {
        tableHeight: 300
      },
      storeType: [],
      list: data,
      brandListData: [],  
    };
  },
  mounted() {
    this.initTable(15);
    this.$refs.form.resetFields();
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.title = "编辑政策";
    } else {
      this.list.tableInfoList = [];
      this.title = "新增政策";
    }
    this.initData()
  },
  destroyed() {
    this.$bus.$off();
  },
  methods: {
    ...table,
    async initData() {
      this.list.tableInfoList = []
      this.list.data = []
      await this.getBrandList()
      await this.getStoreList()
      await this.getInfo();
      
    },
    getBrandList() {
      this.$ajaxGet('/product/common/supplier_brand').then(data => {
        this.list.brandList = data
      })
    },
    getStoreList() {
      this.$ajaxGet('storeType/findAll').then(data => {
        this.storeType = data.map(item => {
          let obj = { storeTypeId: item.id, storeTypeName: item.name }
          return obj
        })
      })
    },
    getInfo() {
      if (!this.id) return
      this.status = 'loading'
      this.$ajaxGet(`/setting/fund_policy/detail/${this.id}`).then(res => {
        const { beginDate, createDate, endDate, policyName, brandList } = res
        this.form.name = policyName
        this.form.date = [formatDate(beginDate), formatDate(endDate)];
        this.inputModel = brandList.map(item => item.brandId)
        this.brandListData = brandList.map(item => {
          return {
            brandId: item.brandId,
            brandName: item.brandName,
            policyItems: item.policyItems.map(p => {
              let { brandId, brandName, coefficient, maxQuantity, storeTypeId, storeTypeName} = p
              return { brandId, brandName, coefficient, maxQuantity, storeTypeId, storeTypeName}
            })
          }
        })
        this.status = 'pass'
      }).catch(err => {
        console.error(err)
        this.status = 'error'
      })
    },
    getTableData() {
      this.list.data = []
      this.list.tableInfoList.forEach(item => {
        this.list.columns = [
          {
            title: '品牌',
            key: "brandName",
            align: 'left',
            minWidth: 100,
          },{
            title: '门店类型',
            key: "brandList",
            align: 'left',
            minWidth: 140,
            render: (h, p) => {
              return p.row.brandList.map(item => {
                return <div style='height: 32px;line-height:32px;' class='borderB' >{item.storeTypeName}</div>
              })
            }
          },{
            title: '基金计算条数上限(条/月)',
            key: "brandList",
            align: 'left',
            render: (h, p) => {
              return p.row.brandList.map((item, idx) => {
                return h('div', [
                  h('InputNumber', {
                    props: {
                      value: item.maxQuantity,
                      min: 0,
                      max: 9999,
                      size: "middle"
                    },
                    on: {
                      "on-change": (e) => {
                        item.maxQuantity = Number(e)
                        this.$set(p.row.brandList, idx, item);
                        this.$set(this.list.data, p.index, p.row);
                      }
                    }
                  })
                ])
              })
            }
          },{
            title: '单条轮胎系数',
            key: "brandList",
            align: 'left',
            render: (h, p) => {
              return p.row.brandList.map((item, idx) => {
                return h('div', [
                  h('InputNumber', {
                    props: {
                      value: item.coefficient,
                      min: 0,
                      max: 9999,
                      size: "middle"
                    },
                    on: {
                      "on-change": (e) => {
                        item.coefficient = Number(e)
                        this.$set(p.row.brandList, idx, item);
                        this.$set(this.list.data, p.index, p.row);
                      }
                    }
                  })
                ])
              })
            }
          }
        ]
        let storeType = getOriginData(item.storeType)
        let hasData = this.brandListData.find(b => b.brandId == item.brandId)
        if (this.id && hasData) {
          storeType = hasData.policyItems
        }
        this.list.data.push({
          brandId: item.brandId,
          brandName: item.brandName,
          brandList: storeType.map(i => {
            i.brandId = item.brandId
            i.brandName = item.brandName
            i.coefficient = i.coefficient || 0
            i.maxQuantity = i.maxQuantity || 0
            return i
          })
        })
      });
    },
    onChange(s) {
      s.map(item => {
        let b = this.list.brandList.find(a => {
          return item == a.brandId;
        });
        let c = this.list.tableInfoList.find(v => {
          return b.brandId == v.brandId;
        });
        if (!c) {
          this.list.tableInfoList.push(b);
        }
      });
      let all = getOriginData(this.list.brandList).map(item => {
        const { brandId, brandName, id } = item
        item.data = []
        item.columns = []
        item.headerList = [{ title: '基金计算条数上限(条/月)', key: 'maxQuantity' }, { title: '单条轮胎系数', key: 'coefficient' }]
        item.storeType = this.storeType
        return item
      });
      this.list.tableInfoList = all.filter(e => {
        let v = s.find(i => i == e.brandId);
        if (!v) {
          e.data = [];
        }
        return v;
      });
      this.getTableData();
    },
    getParamList() {
      let arr = []
      this.list.data.forEach(item => {
        arr = arr.concat(item.brandList)
      })
      return arr
    },
    onSave() {
      if (this.isDisabled) return;
      this.$refs["form"].validate(valid => {
        if (valid) {
          let arr = this.getParamList();
          this.isDisabled = true;
          let url = this.id ? "/setting/fund_policy/modify" : "/setting/fund_policy/save";
          let text = this.id ? "编辑" : "新增";
          let param = {
            policyName: this.form.name || "",
            id: this.id,
            fundPolicyItems: arr || []
          };
          if (this.form.date[0])
            param.beginDate = formatDate(this.form.date[0]) + " 00:00:00";
          if (this.form.date[1])
            param.endDate = formatDate(this.form.date[1]) + " 23:59:59";
          // if (this.id) this.toStageData.id = this.id;
          this.$jsonPost(url, param)
            .then(data => {
              this.$Notice.success({
                title: `${text}成功`
              });
              this.$router.push("/policy/fund/list");
            })
            .catch(() => {
              this.isDisabled = false;
            });
        }
      });
    },
    jumpPrevPage() {
      this.$router.back();
    }
  }
};
</script>
